// 封装组件
<template>
  <div class="treeTransfer">
    <!-- 左边 -->
    <div class="leftLay">
      <div class="titleLay">
        <p class="leftTitle">{{props.fromTitle}}</p>
        <el-button link plain type="primary" size="small"></el-button>
      </div>
      <!-- 搜索 -->
      <div class="leftInput">
        <el-input
            v-if="props.fromSearch"
            v-model="leftSearch"
            class="w-50 m-2"
            placeholder="搜索"
            clearable
            :prefix-icon="Search" />
      </div>
      <el-tree
          class="leftTree"
          ref="treeRef"
          show-checkbox
          check-strictly
          highlight-current
          default-expand-all
          :data="props.fromData"
          :node-key="props.nodeKey"
          :expand-on-click-node="false"
          :props="{
            class: getLeftTreeNode,
            label: 'name',
            disabled: 'transfer',
            children: 'children',
            }"
          @check-change="handleFromCheckChange"
      >
      </el-tree>
    </div>
    <!-- 中间按钮 -->
    <div class="midLay">
      <div class="btnToRight" @click="toRight()">
        <el-button :icon="Right" type="primary" >增加</el-button>
      </div>
      <div class="btnToLeft" @click="toLeft()">
        <el-button :icon="Back" type="danger" >删除</el-button>
      </div>
    </div>
    <!-- 右边 -->
    <div class="rightLay">
      <div class="titleLay">
        <p class="rightTitle">{{props.toTitle}}</p>
        <el-button link plain type="danger" size="small"></el-button>
      </div>
      <!-- 搜索 -->
      <div class="rightInput">
        <el-input
            v-if="props.toSearch"
            v-model="rightSearch"
            class="w-50 m-2"
            placeholder="搜索"
            clearable
            :prefix-icon="Search"
        />
      </div>

      <el-table ref="rightRef" class="rightTable" :data="holdData" @selection-change="handleRightSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column :prop="'name'" header-align="center" align="center" :label="props.toName" />
        <template #empty>暂无数据</template>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
//@ts-nocheck    解决ts类型报红
import {ref, onMounted, effect} from 'vue';
import {MessageBox, Search} from '@element-plus/icons-vue';
import { Right, Back } from '@element-plus/icons-vue';
import {ElMessageBox, ElTable} from "element-plus";

interface Props {
  nodeKey: string,
  toData: any,
  fromData: any,
  defaultProps?: {
    label: 'label',
    children: 'children',
  },
  toSearch: boolean | false,
  fromSearch: boolean | false,
  toName: string | '名称',
  toTitle: any,
  fromTitle: any,
  onToRight: any,
  onToLeft: any,
}

const props = defineProps<Props>();

const leftSearch = ref('');
const rightSearch = ref('');

// 定义emit
const emit = defineEmits(['checkVal']);
const treeRef = ref();
const rightRef = ref<InstanceType<typeof ElTable>>()

// 右侧数据
const holdData = ref([]);
const waitToData = ref([]);
const rightSelection = ref([]);

const initToData = () => {
  if (holdData.value.length > 0) {
    const keys = [];
    holdData.value.forEach(item => {
      keys.push(item.id);
    });

    console.log('--- init transfer: ', keys)
    treeRef.value.setCheckedKeys(keys);
  }
}

onMounted(() => {
  holdData.value = props.toData || [];
  initToData();
});

const getLeftTreeNode = (data: any, node: Node) => {
  if (data.transfer) {
    return 'waitSave'
  }
  return null
}

const handleRightSelectionChange = (val: any) => {
  rightSelection.value = val;
  console.log('--- handleRightSelectionChange: ', rightSelection.value)
}

const handleFromCheckChange = (data: Tree,
                               checked: boolean,
                               indeterminate: boolean) => {
  console.log(data.id, checked, indeterminate);
  if (checked) {
    if (!data.transfer) {
      waitToData.value.push(data);
    }
  } else {
    waitToData.value = waitToData.value.filter(item => item.id != data.id);
  }
  console.log('------ waitToData: ', waitToData.value);
}

const showInfo = (content: string) => {
  ElMessageBox.alert(content, '温馨提示', {
    confirmButtonText: '确定',
  })
}

// 去右边
const toRight = async () => {
  if (waitToData.value.length > 0) {
    if (props.onToRight) {
      const success = await props.onToRight(waitToData.value);
      if (success) {
        waitToData.value.forEach(item => {
          item.transfer = true;
          holdData.value.push({
            id: item.id,
            name: item.name,
            type: item.type,
          });
        })

        waitToData.value = [];
        console.log('------ to right, hold data: ', holdData.value);
      }
    }
  } else {
    showInfo('请选择需要增加的资源！');
  }
}

const contains = (arr: any, key: string) => {
  return arr.find(item => item.id === key);
}

const handleLeft = (doData: any, selData: any) => {
  doData.forEach(item => {
    if (contains(rightSelection.value, item.id)) {
      item.transfer = false;
    }
    if (item.transfer) {
      selData.push(item.id);
    }

    if (item.children && item.children.length > 0) {
      handleLeft(item.children, selData);
    }
  })
}

// 去左边
const toLeft = async () => {
  if (rightSelection.value && rightSelection.value.length > 0) {
    if (props.onToLeft) {
      const success = await props.onToLeft(rightSelection.value);
      if (success) {
        const selData = [];

        handleLeft(props.fromData, selData);
        holdData.value = holdData.value.filter(item => !rightSelection.value.some(rItem => rItem.id == item.id));

        treeRef.value.setCheckedKeys(selData);
        rightSelection.value = [];
        rightRef.value!.clearSelection()
      }
    }
  } else {
    showInfo('请选择需要移除的资源！');
  }
};

const updateTransfer = (data: any) => {
  if (treeRef.value) {
    holdData.value = data;
    initToData();
  }
}

const getToData = () => {
  return holdData.value;
};

defineExpose({
  updateTransfer,
  getToData,
})

</script>

<style>
:deep(.el-table__empty-block) {
  width: 100%;
  min-width: 100%;
  max-width: 100%;
}

.waitSave > .el-tree-node__content {
  color: #FF0000;
}

.hasSave > .el-tree-node__content {
  color: #00FF00;
}

.treeTransfer {
  display: flex;
  flex-direction: row;
  height: 100%;
  padding: 8px 0 8px;
}

.leftLay,.rightLay {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 8px;
  border: 1px solid #49a9ee;
  border-radius: 4px;
}

.leftTree,.rightTable {
  flex: 1;
}

.titleLay {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.leftTitle,.rightTitle {
  margin: 1px 0 6px;
}

.rightTable {
  flex: 1;
  border: none;
}

.midLay {
  display: flex;
  flex-direction: column;
  margin: 0 16px;
  justify-content: center;
}

.btnToRight {
  margin-bottom: 32px;
}

.btnToLeft {
  margin-top: 32px;
}

</style>
